// 用户模块路由处理函数

// 引入数据库模块
const db = require('../mysql/index')
// 密码加密模块
const bcrypt = require('bcryptjs')
// 引入jwt
const jwt = require('jsonwebtoken')
const secretKey = 'rent_car'    // 密钥

// 后台
// 获取会员列表
exports.memberList = (req, res) => {
    let { pageNumber, pageSize, username, real_name, card_id } = req.body
    // 需要提交的参数
    let paramsObj = {
        username,
        real_name,
        card_id
    }
    let sql = ''
    for (const key in paramsObj) {
        if (paramsObj[key] !== undefined && paramsObj[key] !== '') {
            sql = `SELECT id, username, real_name, card_id, rent_order, deposit, isIdentification, drivingLicence FROM user WHERE ${key} like "%${paramsObj[key]}%"`
            break
        } else {
            sql = 'SELECT id, username, real_name, card_id, rent_order, deposit, isIdentification, drivingLicence FROM user'
        }
    }
    // 分页
    pageSize = Number(pageSize)
    const offset = (Number(pageNumber) - 1) * pageSize
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 0) return res.send({ code: 201, message: '会员列表为空' })
        // 布尔值处理
        result.forEach(item => {
            item.isIdentification = item.isIdentification ? true : false
            item.drivingLicence = item.drivingLicence ? true : false
        });
        let data = result.slice(offset, offset + pageSize)
        return res.send({
            code: 200,
            message: '获取会员列表成功',
            data,
            total: result.length
        })
    })
}
// 删除会员
exports.deleteMember = (req, res) => {
    const id = req.query.id
    const sql = 'DELETE FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('删除失败')
        return res.cc('删除成功', 200)
    })
}
// 获取会员详情
exports.getMemberDetail = (req, res) => {
    const id = req.query.id
    const sql = 'SELECT username, real_name, card_id, isIdentification, bank_number, drivingLicence, drivingLicence_id, phone, deposit FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('获取详情失败')
        return res.send({
            code: 200,
            message: '获取会员详情成功',
            data: result[0]
        })
    })
}





// web端
// 注册
exports.register = (req, res) => {
    const userInfo = req.body
    // 判断用户信息是否合法
    if (!userInfo.username || !userInfo.password) return res.cc('用户名或密码不合法')
    // 用户名是否被占用
    const userName = 'SELECT * FROM user WHERE username = ?'
    db.query(userName, userInfo.username, (err, result) => {
        // sql执行失败
        if (err) return res.cc(err)
        // 用户名存在
        if (result.length > 0) return res.cc('用户名已存在')
        // 用户名不存在（可以注册）
        // 对密码进行加密 bcrypt.hashSync(要加密的密码, 长度)
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        // 添加用户
        const sqlAddUser = 'INSERT INTO user set ?'
        db.query(sqlAddUser, { username: userInfo.username, password: userInfo.password }, (err, result) => {
            if (err) return res.cc(err)
            // 添加成功
            if (result.affectedRows === 1) return res.cc('注册成功', 200)
        })
    })
}
// 登录
exports.login = (req, res) => {
    const userInfo = req.body
    if (!userInfo.username || !userInfo.password) return res.cc('用户名或密码不合法')
    // 查询是否用户存在
    const sqlUser = 'SELECT * FROM user WHERE username = ?'
    db.query(sqlUser, userInfo.username, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 0) return res.cc('该用户不存在')
        // 用户存在
        if (result.length === 1) {
            // 判断密码是否正确
            // 用户输入的密码,和数据库中存储的密码进行对比
            const compareResult = bcrypt.compareSync(userInfo.password, result[0].password)
            if (!compareResult) return res.cc('输入的密码有误')
            // 登录成功
            // 进行加密生成token，密码和用户头像不用加在token里面
            const user = { ...result[0], password: '', user_pic: '' }
            const tokenStr = 'Bearer ' + jwt.sign(user, secretKey, { expiresIn: '7d' })
            // 将token保存
            const saveToken = 'UPDATE user SET token = ? WHERE id = ?'
            db.query(saveToken, [tokenStr, result[0].id], (saveErr, saveResult) => {
                if (saveErr) return res.cc(saveErr);
                if (saveResult.affectedRows !== 1) return res.cc('保存token失败')
            })
            return res.send({
                code: 200,
                message: '登录成功',
                token: tokenStr,
                id: result[0].id
            })
        }
    })
}
// 获取用户信息
exports.getUserInfo = (req, res) => {
    const token = req.body
    const sqlUser = 'SELECT * FROM user WHERE token = ?'
    db.query(sqlUser, token.token, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('暂未登录')
        if (result.length === 1) {
            // 删除不用的数据
            Reflect.deleteProperty(result[0], 'password')
            Reflect.deleteProperty(result[0], 'real_name')
            Reflect.deleteProperty(result[0], 'card_id')
            Reflect.deleteProperty(result[0], 'deposit')
            Reflect.deleteProperty(result[0], 'isIdentification')
            Reflect.deleteProperty(result[0], 'drivingLicence')
            Reflect.deleteProperty(result[0], 'phone')
            Reflect.deleteProperty(result[0], 'money_code')
            Reflect.deleteProperty(result[0], 'bank_name')
            Reflect.deleteProperty(result[0], 'bank_number')
            Reflect.deleteProperty(result[0], 'drivingLicence_id')
            Reflect.deleteProperty(result[0], 'rent_order')
            result[0].user_pic = 'http://62.234.193.89:3007/' + result[0].user_pic;
            return res.send({
                code: 200,
                message: '获取用户信息成功',
                data: result[0]
            })
        }
    })
}
// 退出登录
exports.logout = (req, res) => {
    const id = req.query.id;
    const sql = 'UPDATE user SET token = "" WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err);
        if (result.affectedRows !== 1) return res.cc('更新token失败')
        return res.send({
            code: 200,
            message: '退出登录成功'
        })
    })
}
// 忘记密码
exports.forgetPassword = (req, res) => {
    const phone = req.body.phone
    let password = req.body.password
    // 查询用户是否存在
    const sql = 'SELECT username FROM user WHERE username = ?'
    db.query(sql, phone, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 0) return res.cc('该用户不存在')
        if (result.length === 1) {
            // 用户存在
            const updateSql = 'UPDATE user set password = ? WHERE username = ?'
            password = bcrypt.hashSync(password, 10)
            db.query(updateSql, [password, phone], (err1, result1) => {
                if (err1) return res.cc(err1)
                if (result1.affectedRows === 1) return res.cc('修改密码成功', 200)
            })
        }
    })
}
// 修改密码
exports.updatePassword = (req, res) => {
    let { id, oldPass, newPass } = req.body
    const sql = 'SELECT password FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 1) {
            // 用户输入的密码,和数据库中存储的密码进行对比
            const compareResult = bcrypt.compareSync(oldPass, result[0].password)
            if (!compareResult) return res.cc('旧密码错误，请重新输入')
            // 修改密码
            const updateSql = 'UPDATE user set password = ? WHERE id = ?'
            // 加密存储
            newPass = bcrypt.hashSync(newPass, 10)
            db.query(updateSql, [newPass, id], (err1, result1) => {
                if (err1) return res.cc(err1)
                if (result1.affectedRows === 1) return res.cc('密码修改成功，请重新登录', 200)
            })
        }
    })


}
// 绑定手机号
exports.bindPhone = (req, res) => {
    const phone = req.body.phone
    const id = req.body.id
    const sql = 'UPDATE user set phone = ? WHERE id = ?'
    db.query(sql, [phone, id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('绑定手机号失败')
        if (result.affectedRows === 1) {
            return res.cc('绑定手机号成功', 200)
        }
    })
}
// 设置资金密码
exports.moneyCode = (req, res) => {
    let password = req.body.password
    const id = req.body.id
    password = bcrypt.hashSync(password, 10)
    const sql = 'UPDATE user set money_code = ? WHERE id = ?'
    db.query(sql, [password, id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('设置资金密码失败')
        if (result.affectedRows === 1) {
            return res.cc('设置资金密码成功', 200)
        }
    })
}
// 添加银行卡
exports.addBankCard = (req, res) => {
    const { id, account_name, account_bank, account_number, account_phone } = req.body
    const sql = 'SELECT real_name FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result[0].real_name === null || result[0].real_name === '') return res.cc('您还没有实名认证，请先实名认证')
        if (result[0].real_name != account_name) return res.cc('开户名与用户不匹配')
        const sqlAdd = 'UPDATE user set real_name = ?, bank_name = ?, bank_number = ?, phone = ? WHERE id = ?'
        db.query(sqlAdd, [account_name, account_bank, account_number, account_phone, id], (err1, result1) => {
            if (err1) return res.cc(err1)
            if (result1.affectedRows !== 1) return res.cc('添加银行卡失败')
            return res.cc('添加银行卡成功', 200)
        })
    })
}
// 获取银行卡信息
exports.getBankCard = (req, res) => {
    const id = req.query.id
    const sql = 'SELECT bank_name, bank_number FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        let data = {}
        if (result[0].bank_name && result[0].bank_number) {
            data = result
        } else {
            data = []
        }
        return res.send({
            code: 200,
            message: '获取银行卡信息成功',
            data
        })
    })
}
// 身份认证
exports.authentication = (req, res) => {
    const { id, real_name, card_id, drivingLicence_id } = req.body
    if (card_id && !drivingLicence_id) {
        const sql = 'UPDATE user set real_name = ?, card_id = ?, isIdentification = 1 WHERE id = ?'
        db.query(sql, [real_name, card_id, id], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc('认证失败')
            return res.cc('认证成功', 200)
        })
    }
    if (drivingLicence_id && !card_id) {
        const sql = 'UPDATE user set drivingLicence_id = ?, drivingLicence = 1 WHERE id = ? and real_name = ?'
        db.query(sql, [drivingLicence_id, id, real_name], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows !== 1) return res.cc('认证失败，请先身份认证或保持姓名一致')
            return res.cc('认证成功', 200)
        })
    }
}
// 获取身份认证信息
exports.getIdTentInfo = (req, res) => {
    const id = req.query.id
    const sql = 'SELECT real_name, card_id, drivingLicence_id FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('获取身份信息失败')
        let data = {}
        if (result[0].real_name && result[0].card_id || result[0].real_name && result[0].drivingLicence_id) {
            data = result
        } else {
            data = []
        }
        return res.send({
            code: 200,
            message: '获取身份信息成功',
            data
        })
    })
}
// 查看是否完成认证
exports.isCompleteCertification = (req, res) => {
    const id = req.query.id
    const sql = 'SELECT isIdentification, drivingLicence, bank_number as bindBank FROM user WHERE id = ?'
    db.query(sql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('Error')
        let data = result[0]
        data.isIdentification ? data.isIdentification = true : data.isIdentification = false
        data.drivingLicence ? data.drivingLicence = true : data.drivingLicence = false
        data.bindBank ? data.bindBank = true : data.bindBank = false
        return res.send({
            code: 200,
            message: '获取信息成功',
            data
        })
    })
}
